package ccm.common;

import ccm.component.override.JSpinner;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;

public final class Utils
{
    private Utils()
    {

    }

    public static String timeFormatter(long timeUs)
    {
        return String.format("%dh%02dm%02ds%03dms",timeUs/1000000/60/60,timeUs/1000000/60%60,timeUs/1000000%60,timeUs/1000%1000);
    }

    static public File[] getFileList(String dir)
    {
        return Utils.getFileList(dir,".bmp");
    }

    static public File[] getFileList(String dir,String ext)
    {
        ArrayList<File> fl=new ArrayList<File>(Arrays.asList(Objects.requireNonNull(new File(dir).listFiles())));
        fl.removeIf(e->(!e.getName().endsWith(ext)||e.isDirectory()));
        fl.sort(Comparator.comparingInt(o->f(o.getName())));
        return fl.toArray(new File[0]);
    }

    static private Integer f(String filename)
    {
        int x=filename.indexOf(".");
        String string2=filename.substring(0,x);
        char[] cs=string2.toCharArray();
        StringBuilder builder=new StringBuilder();
        for(char c: cs)
        {
            if(Character.isDigit(c))
            {
                builder.append(c);
            }
        }
        return Integer.parseInt(builder.toString());
    }

    /**
     * 设置 JSpinner的value
     */
    public static void setJSpinnerValue(JSpinner jSpinner,Number number)
    {
        if(jSpinner==null)
        {
            return;
        }
        SpinnerNumberModel spinnerNumberModel=((SpinnerNumberModel)jSpinner.getModel());
        if(number.floatValue()>((Number)spinnerNumberModel.getMaximum()).floatValue())
        {
            spinnerNumberModel.setValue(spinnerNumberModel.getMaximum());
        }
        else if(number.floatValue()<((Number)spinnerNumberModel.getMinimum()).floatValue())
        {
            spinnerNumberModel.setValue(spinnerNumberModel.getMinimum());
        }
        else
        {
            spinnerNumberModel.setValue(number);
        }
    }

    public static Font fontResize(Font font,float resize)
    {
        return new Font(font.getName(),font.getStyle(),(int)(font.getSize()*resize));
    }


    static public String speedString(long l,boolean b,boolean s)
    {
        final String c=(b?'b':'B')+(s?"/s":"");
        if(l<=0)
        {
            return String.format("%.0f %s",0.0,c);
        }
        if(l<1e3)
        {
            return String.format("%.0f %s",l*1.0,c);
        }
        else if(l<1e6)
        {
            return String.format("%.2f K%s",l/1e3,c);
        }
        else if(l<1e9)
        {
            return String.format("%.2f M%s",l/1e6,c);
        }
        return String.format("%.2f G%s",l/1e9,c);
    }
}
